/*
 *  StochasticConcreteNote.cpp
 *  SoundController0002
 *
 *  Created by jiro on 11/10/10.
 *  Copyright 2011 jiro music. All rights reserved.
 *
 */

#include "StochasticConcreteNote.h"

namespace sc
{
namespace system0039
{

	StochasticConcreteNote::StochasticConcreteNote()
	{}
	
	void StochasticConcreteNote::AddNote( const ConcreteNote& note, double probablity )
	{
		notes.push_back( note );
		probablities.push_back( probablity );
	}

	void StochasticConcreteNote::Clear()
	{
		notes.clear();
		probablities.clear();
	}

	ConcreteNote StochasticConcreteNote::GetConcreteNote() const
	{
		double randomValue = ::sc::RandomValueGenerator::GetValue( 0.0, 1.0 );
		double lowerValue = 0.0;
		double higherValue = 0.0;
		double fraction = 0.0;

		int count = notes.size();
		for ( int i = 0; i < count; i++ )
		{
			fraction += probablities[ i ];
		}

		for ( int i = 0; i < count; i++ )
		{
			higherValue += probablities[ i ] / fraction;
			if ( lowerValue <= randomValue and randomValue < higherValue )
			{
				return notes[ i ];
			}
			lowerValue = higherValue;
		}
		return notes.back();
	}

	std::string StochasticConcreteNote::ToString( int tabCount ) const
	{
		std::stringstream ss;
		std::string tabs;
		for ( int i = 0; i < tabCount; i++ )
		{
			tabs.append( "\t" );
		}
		ss << tabs << "StochasticConcreteNote:\n";
		ss << tabs << "\t" << "count: " << notes.size() << "\n";
		for ( int i = 0; i < notes.size(); i++ )
		{
			ss << tabs << "\t" << notes[ i ].ToString( tabCount )
			   << "\n" << tabs << "\tprobablity: " << probablities[ i ]
			   << "\n";
		}
		return ss.str();
	}

}
}
